﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Base;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.WeiXin;
using Atmk.WaterMeter.MIS.Commons.Interfaces.WeiXin;
using Atmk.WaterMeter.MIS.Commons.ViewModels;
using Atmk.WaterMeter.MIS.Controllers.Pay.Base;
using Atmk.WaterMeter.MIS.Datas;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Atmk.WaterMeter.MIS.Controllers.Pay
{
    /// <summary>
    /// 微信小程序支付功能接口
    /// </summary>
    [Wx_Authorize]
    public class Wx_SmallRoutine_PayPaymentController : BaseApiController
    {
        private static ILogger<Wx_SmallRoutine_PayPaymentController> _Logger;
        private readonly IWxPayment _wxPayment;
        private readonly IWxRechargeRecordLogic _wxRechargeRecord;


        /// <inheritdoc />
        public Wx_SmallRoutine_PayPaymentController(
            IWxPayment wxPayment,
            IWxRechargeRecordLogic wxRechargeRecord,
            ILogger<Wx_SmallRoutine_PayPaymentController> logger
        )
        {
            _wxPayment = wxPayment;
            _wxRechargeRecord = wxRechargeRecord;
            _Logger = logger;
        }

        /// <summary>
        /// 支付订单生成指令
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        [HttpPost("/api/{X-Version}/pay/wx/payment")]
        public async Task<IActionResult> PayMentNote([FromBody] dynamic obj)
        {
            var url = WxConfigManage.CallbackUrlDemo;

            if (obj == null)
                _Logger.LogDebug("参数为空");
            else
            {
                string message = obj.ToString();
                _Logger.LogDebug("创建订单指令", message);
            }
            //#if DEBUG
            //            url = WxConfigManage.CallbackUrlTest;
            //#endif
            string meterNumber, openid;
            var amount = -1;
            try
            {
                meterNumber = Convert.ToString(obj.meterNumber);
                openid = Convert.ToString(obj.openid);
                amount = Convert.ToInt32(obj.amount);
            }
            catch (Exception)
            {
                return Ok(new
                {
                    errcode = 1,
                    msg = $"订单生成失败:传入参数错误"
                });
            }
            const string type = "publish";
            //生成付款单发送，并返回参数
            var respon = await _wxPayment.SmallRoutineUnifiedorder(WxConfigManage.GetAppid(type), openid,
                WxConfigManage.GetMchId(type).Trim(), url, WxConfigManage.GetMchIdKey(type), amount);
            if (respon.err_code.Trim().Length > 0)
            {
                return Ok(new { errcode = 1, msg = $"订单生成失败:{respon.err_code_des}" });
            }
            var data = respon.ToPayDataVm();
            try
            {
                //添加本地订单记录
                var result = _wxRechargeRecord.CreateOrderRecored(openid, meterNumber, respon.out_trade_no, amount);
                return result.Success
                    ? Ok(new { errcode = 0, msg = "订单生成", data })
                    : Ok(new { errcode = 1, msg = $"订单保存时失败:{result.ErrorMessage}" });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"订单保存时失败:{e.Message}" });
            }

        }
        /// <summary>
        /// 查询缴费记录
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="meterNumber"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/pay/wx/records")]
        public async Task<IActionResult> ChargingRecords(string openid, string meterNumber = "", string startTime = "", string endTime = "")
        {
            try
            {
                var array =
                    await _wxRechargeRecord.ChargingRecords(openid, meterNumber);
                var records = array.Select(r => r.ToWxSrOrderVm()).ToList();
                return Ok(new { errcode = 0, msg = "查询成功", data = new { records } });
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"查询失败:{e.Message}" });
            }
        }

        /// <summary>
        /// 查询缴费记录
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="meterNumber"></param>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <returns></returns>
        [HttpGet("/api/{X-Version}/pay/wx/selectDosage")]
        public IActionResult selectDosage(string openid, string meterNumber = "", string startTime = "", string endTime = "")
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var ownerid=_context.Meter.FirstOrDefault(m => m.MeterNumber == meterNumber)?.OwnerId;
                    if (string.IsNullOrWhiteSpace(ownerid))
                    {
                        return Ok(new { errcode = 1, msg = $"查询失败:没找到业主ID" });
                    }
                    var array = _context.OrderDetail.Where(m => m.CostType == 1 && m.OwnerId == ownerid).OrderByDescending(m=>m.MeterNumber).ThenByDescending(m=>m.CreateTime).ToList();
                    return Ok(new { errcode = 0, msg = "查询成功", data = new { array },total= array.Sum(m=>m.WaterVolume) });
                }
            }
            catch (Exception e)
            {
                _Logger.LogError(e.Message, e);
                return Ok(new { errcode = 1, msg = $"查询失败:{e.Message}" });
            }
        }
    }
}